package com.ft.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ft.core.runtime.session.IAuthUser;
import com.ft.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @copyright (C), 2015-2019, XXX有限公司
 * @fileName: AuditMetaObjectHandler
 * @author: 李阳
 * @date: 2019/6/27 3:47
 * @description: 审计源对象自动填充处理器
 * @history: <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
@Slf4j
@Component
public class AuditAndLogicDeletedMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //避免使用metaObject.setValue()
        final IAuthUser user = SecurityUtils.getUser();
        final String userName = user == null ? "无" : user.getUserName();
        final Date now = new Date();
        if (metaObject.hasGetter("createdTime") &&
                null == metaObject.getValue("createdTime")) {
            this.setInsertFieldValByName("createdTime", now, metaObject);
        }
        if (metaObject.hasGetter("createdBy") &&
                null == metaObject.getValue("createdBy")) {
            this.setInsertFieldValByName("createdBy", userName, metaObject);
        }
        if (metaObject.hasGetter("updatedTime") &&
                null == metaObject.getValue("updatedTime")) {
            this.setInsertFieldValByName("updatedTime", now, metaObject);
        }
        if (metaObject.hasGetter("updatedBy") &&
                null == metaObject.getValue("updatedBy")) {
            this.setInsertFieldValByName("updatedBy", userName, metaObject);
        }
        // 逻辑删除插入时为false
        this.setInsertFieldValByName("deleted", false, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        final IAuthUser user = SecurityUtils.getUser();
        final String userName = user == null ? "无" : user.getUserName();
        final Date now = new Date();
        this.setUpdateFieldValByName("updatedTime", now, metaObject);
        this.setUpdateFieldValByName("updatedBy", userName, metaObject);
    }
}
